package cn.com.scitc.licenseplateback.endpointAdvice;


import cn.com.scitc.licenseplateback.absExcetion.ElementNotFoundException;
import cn.com.scitc.licenseplateback.absExcetion.ParamInvalidException;
import cn.com.scitc.licenseplateback.absExcetion.TokenException;
import cn.com.scitc.licenseplateback.absExcetion.TokenInvalidation;
import cn.com.scitc.licenseplateback.io.ResultDto;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@ControllerAdvice // 指定这个类是一个监听类，用于监听不同异常输出结果
@RestController
public class EndpointAdvice {

    @ExceptionHandler(ElementNotFoundException.class) // 元素未找到异常
    @ResponseStatus(HttpStatus.NOT_FOUND) // 返回 404
    public ResultDto<Void> elementNotFount(ElementNotFoundException e) {
        return new ResultDto<>(e.getMessage());
    }

    @ExceptionHandler(ParamInvalidException.class) // 参数错误异常
    @ResponseStatus(HttpStatus.BAD_REQUEST) // 返回 400
    public ResultDto<Void> paramInvalid(ParamInvalidException e) {
        return new ResultDto<>(e.getMessage());
    }

    @ExceptionHandler(TokenException.class) // 令牌获取失败
    @ResponseStatus(HttpStatus.UNAUTHORIZED) // 返回 401
    public ResultDto<Void> tokenAbnormity(TokenException e) {
        return new ResultDto<>(e.getMessage());
    }

    @ExceptionHandler(TokenInvalidation.class) // 令牌失效
    @ResponseStatus(HttpStatus.FORBIDDEN) // 返回 403
    public ResultDto<Void> tokenInvalidation(TokenInvalidation e) {
        return new ResultDto<>(e.getMessage());
    }

    @ExceptionHandler(Exception.class) // 未知错误
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 返回 500
    public ResultDto<Void> serverException(Exception e) {
        return new ResultDto<>(e.getMessage());
    }
}
